import React, {Component} from "react";
import {render} from "react-dom";
import {restApiRequest} from "../Public/Api/Public";
import {DatePicker, List, Modal, Toast} from 'antd-mobile';
import Login from '../Public/Components/Login';
import pic_receipt_corner_tag from "../../images/pic_receipt_corner_tag.png";
import receipt_bg_shadow from "../../images/receipt_bg_shadow.png";

export default class OrderPay extends Component {

    constructor(props, context) {
        super(props, context);

        this.state = {
            data: JSON.parse(localStorage.getItem('pay_msg')),
            cell_number: null,
            contact_name: '',
            id_card: '',
            address: '',
            showText: true,
            amount: 1,
            // visible: false,
            travel_date: '',
            value: '',
            coupon: null,
            coupon_list: null,
            visible: false,
            guige: false
        };
        this.user_info_list = [];

        let user_info = {};
        user_info.address = '';
        user_info.id_card = '';
        user_info.contact_name = '';
        this.user_info_list.push(user_info);
        this.onChange = this.onChange.bind(this);

    }

    componentWillMount() {
        this.fetchUserCouponList();
        //默认填充登录手机账号
        let cellNumber = localStorage.getItem('cell_number').replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3");
        this.setState({cell_number: cellNumber});

    }

    componentDidMount() {
        this.setState({});
    }

    //获取优惠券
    fetchUserCouponList() {
        let sessionkey = localStorage.getItem('sessionkey');
        let param = {sessionkey: sessionkey, spec_product_id: this.state.data.spec_product_id, coupon_state: 1};
        let jsonData = restApiRequest.getSign(param);
        let url = '/shop/api/getUserCouponList';
        restApiRequest.fetchp(url, jsonData).then((response) => {
            if (!response.ok) {
                var error = new Error(response.statusText);
                error.response = response;
                throw error;

            } else {
                return response.json();
            }
        }).then((response_json) => {
            // console.log(response_json,'----->response_json')
            if (response_json.code == '0000') {
                this.setState({coupon_list: response_json.data});
                console.log(this.state.coupon_list.length, '----->this.state.coupon_list.length')
            } else {
            }

        }).catch((ex) => {
            //ex.response.text().then((theText) => console.log(theText));
            console.log(ex);
        });
        // });

    }

    //购买数量
    onChange(val) {
        let amout = this.state.amount;
        if (amout > val) {
            this.user_info_list.pop();
        } else {
            let user_info = {};
            this.user_info_list.push(user_info);
        }
        this.setState({
            amount: val
        })
    }

    onMinus() {
        let val = this.state.amount === 1 ? 1 : --this.state.amount;
        //检查优惠券
        if (this.state.coupon != null) {
            if (this.state.coupon.coupon_type != undefined) {
                let total_money = this.state.data.selling_price * this.state.amount;
                if (this.state.coupon.order_min_total_money > total_money) {
                    Toast.info('订单金额小于优惠券允许最低金额', 2);
                    ++this.state.amount;
                    return;
                }
            }
        }
        this.setState({amount: val});
        this.user_info_list.pop();
    }

    onPlus() {
        //检查优惠券
        if (this.state.coupon != null) {
            if (this.state.amount == this.state.coupon.order_max_count) {
                Toast.info('优惠券限制了订单最大数量为：' + this.state.coupon.order_max_count, 2);
                return;
            }
        }
        // 判断订单是否需要身份证
        let val = this.state.data.order_form.indexOf('id_card') != -1 ?
            this.state.amount === 10 ? 10 : ++this.state.amount :
            this.state.amount === 20 ? 20 : ++this.state.amount;

        this.setState({amount: val})
        let user_info = {};
        this.user_info_list.push(user_info);
    }


    //检查支付信息
    checkPay() {

        if (this.state.travel_date == '') {
            return Toast.info('请输入出行时间', 2);
        }

        let cell_number = this.state.cell_number.replace(/\s+/g, "");
        if (cell_number == null || cell_number.length != 11) {
            return Toast.info('请输入完整手机号', 2);
        }
        let reg = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
        if (!reg.test(cell_number)) {
            return Toast.info('手机号格式错误', 2);
        }

        console.log(this.user_info_list);
        for (let i = 1; i <= this.state.amount; i++) {

            if (this.state.data.order_form.indexOf('contact_name') != -1) {
                if (this.user_info_list[i - 1]['contact_name'] == '' || this.user_info_list[i - 1]['contact_name'] == undefined) {
                    return Toast.info('请输入用户姓名', 2);
                }
            }
            if (this.state.data.order_form.indexOf('id_card') != -1) {
                if (this.user_info_list[i - 1].id_card == '' || this.user_info_list[i - 1].id_card == undefined || this.user_info_list[i - 1].id_card.length != 18) {
                    return Toast.info('请输入18位有效身份证号', 2);
                }
            }
            if (this.state.data.order_form.indexOf('address') != -1) {
                if (this.user_info_list[i - 1].address == '' || this.user_info_list[i - 1].address == undefined) {
                    return Toast.info('请输入有效地址', 2);
                }
            }
        }
        // Toast.info('该支付了' + cell_number, 2);
        this.setState({showText: false});
        this.fetchTestOrder();
        // this.setState({
        //   visible: true
        // })

    }


    fetchTestOrder() {
        let url = '/shop/api/addOrder';
        let sessionKey = localStorage.getItem('sessionkey');
        let user_cell_number = this.state.cell_number.replace(/ /g, '');
        let time = Date.parse(this.state.travel_date) / 1000
        let param = {
            major_product_id: this.state.data.major_product_id,
            major_product_short_name: this.state.data.title,
            spec_product_id: this.state.data.spec_product_id,
            spec_date_id: this.state.data.spec_date_id ? this.state.data.spec_date_id : 0,
            user_cell_number: user_cell_number,
            amount: this.state.amount,
            user_info_list: this.user_info_list,
            sessionkey: sessionKey,
            travel_date: time,
            openid: window.openid,
        };

        //增加优惠券参数
        if (this.state.coupon) {
            param['user_coupon_id'] = this.state.coupon.user_coupon_id;
        }

        let jsonData = restApiRequest.getSign(param);
        restApiRequest.fetchp(url, jsonData).then((response) => {
            console.log(jsonData)
            if (!response.ok) {
                var error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.json();
            }
        }).then((response_json) => {
            console.log(response_json, '---->wxpay');
            this.setState({showText: true});
            if (response_json.code === '0000') {
                let host = window.location.href;
                if (host.indexOf('zzwx1') != -1) {
                    window.location.href = "http://zzwx1.hidizhu.com/" + 'api/pay/shopPay?order_num=' + response_json.data.out_trade_no;
                } else {
                    window.location.href = "http://weixin.hidizhu.com/" + 'api/pay/shopPay?order_num=' + response_json.data.out_trade_no;
                }
            } else {
                return Toast.info(response_json.msg, 2);
            }
        }).catch((ex) => {
            console.log(ex.message);
        });
    }

    //更新用户信息 list
    updateUserInfoList(info_id, key, value) {
        this.user_info_list[info_id][key] = value;
    }

    passCoupons(coupon) {
        console.log(coupon, '传回的--->coupons')
        this.setState({
            coupon: coupon,
            guige: false
        })
    }


    onBuy = key => (e) => {
        if (this.state.coupon_list != null) {
            e.preventDefault(); // 修复 Android 上点击穿透
            this.setState({
                [key]: true,
            });

        } else {
            this.setState({
                coupon: '暂无可使用的优惠券',
            });
            return Toast.info('暂无可使用的优惠券', 2);
        }
    }

    onClose = key => () => {
        this.setState({
            [key]: false,
        });
    }

    //弹出优惠券选择列表
    popCoupons() {

        if (this.state.coupon_list != null) {
            // Popup.show(
            //     <Coupons CouponsList={this.state.coupon_list}
            //         passCoupons={(coupon) => this.passCoupons(coupon)}
            //         selling_price={this.state.data.selling_price}
            //         amount={this.state.amount}
            //
            //     />, { animationType: 'slide-up', maskClosable: false }
            // );


        } else {
            this.setState({
                coupon: '暂无可使用的优惠券',
            });
            return Toast.info('暂无可使用的优惠券', 2);
        }

    }

    //切换账号成功回调
    onLoginCallback() {
        this.setState({
            visible: false,
            cell_number: localStorage.getItem('cell_number').replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3"),
        });
        this.fetchUserCouponList();
    }

    render() {


        let pages = [];
        for (let i = 0; i < this.state.amount; i++) {
            pages.push(
                <div key={i}>
                    {(this.state.data.order_form.indexOf('contact_name') != -1) ?
                        <div className="order-pay-cell">
                            <div className="order-pay-phone">
                                <section>姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:</section>
                                <input
                                    type="text"
                                    placeholder="请输入姓名"
                                    maxLength={5}
                                    onBlur={(e) => {
                                        this.updateUserInfoList(i, 'contact_name', e.target.value);
                                    }}
                                    className="order-pay-phone-input"
                                />
                            </div>
                            <div className="order-pay-line-solid"/>
                        </div>

                        : null}
                    {(this.state.data.order_form.indexOf('id_card') != -1) ?
                        <div className="order-pay-cell">
                            <div className="order-pay-phone">
                                <section>身份证号:</section>
                                <input
                                    type="tel"
                                    placeholder="请输入18位身份证号"
                                    maxLength={18}
                                    onBlur={(e) => {
                                        this.updateUserInfoList(i, 'id_card', e.target.value);
                                    }}
                                    className="order-pay-phone-input"
                                />
                            </div>
                            <div className="order-pay-line-solid"/>
                        </div>
                        : null}
                    {(this.state.data.order_form.indexOf('address') != -1) ?
                        <div className="order-pay-cell">
                            <div className="order-pay-phone">
                                <section>地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址:</section>
                                <input
                                    type="tel"
                                    placeholder="请输入有效地址"
                                    onBlur={(e) => {
                                        this.updateUserInfoList(i, 'address', e.target.value);
                                    }}
                                    className="order-pay-phone-input"
                                />
                            </div>
                            <div className="order-pay-line-solid"/>
                        </div>
                        : null}

                </div>)
        }

        let totalMoney = (this.state.data.selling_price * this.state.amount).toFixed(2);

        //优惠券引起的价格变化
        if (this.state.coupon) {
            if (this.state.coupon.coupon_type != undefined) {
                if (this.state.coupon.coupon_type == '1') {
                    totalMoney = (parseFloat(totalMoney) - parseFloat(this.state.coupon.reduce_money)).toFixed(2);
                } else if (this.state.coupon.coupon_type == '2') {
                    totalMoney = (parseFloat(totalMoney) * parseInt(this.state.coupon.discount_rate) / 100).toFixed(2);
                }
            }
        }
        let big = '0';
        let small = '0';
        let price_array = totalMoney.split('.');
        big = price_array[0];
        small = price_array[1].substr(0, 1);

        let couponNum = '';
        if (this.state.coupon_list) {
            couponNum = this.state.coupon_list.length;
        }
        // console.log(this.state.coupon,'----------->this.state.coupon')

        const nowTimeStamp = Date.now();
        const now = new Date(nowTimeStamp);
        const utcNow = new Date(now.getTime() + (now.getTimezoneOffset() * 60000));

        let minDate = new Date(nowTimeStamp - 1e7);
        const maxDate = new Date(nowTimeStamp + 1e7);
        if (minDate.getDate() !== maxDate.getDate()) {
            minDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
        }

        return (
            <div className="order-pay-bg">
                {this.state.visible ? <Login onClosedCallback={() => {
                    this.setState({visible: false})
                }} onLoginCallback={() => this.onLoginCallback()}/> : null}
                <div>
                    <section className="order-pay-toptips"/>

                    <section className="order-pay-wrap">
                        <section className="order-pay-title">{this.state.data.title}</section>

                        <div className="order-pay-guide">
                            <section>规格选择:</section>
                            <section>
                                <span>{this.state.data.spec_name}</span><span>{this.state.data.spec_time}</span>
                            </section>
                        </div>
                        <div className="order-pay-line-solid"/>
                        <div className="order-pay-price">
                            <section>单&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;价:</section>
                            <section className="order-pay-price-children">
                                <span>{'￥' + this.state.data.selling_price}</span>
                                {this.state.data.allow_refund == '0' ? <span style={{color: 'yellow'}}>随时退</span> :
                                    <span style={{color: '#D0011B'}}>不可退</span>}
                            </section>
                        </div>
                        <div className="order-pay-line-solid"/>

                        <div className="order-pay-phone">
                            <section>手&nbsp;机&nbsp;号:</section>
                            <input
                                type="tel"
                                placeholder="请输入11位手机号"
                                maxLength={11}
                                onChange={(e) => {
                                    Modal.alert('提示', <div>手机号为用户唯一身份标识，更换后，原有权益不能转移</div>, [
                                        {text: '放弃', onPress: () => console.log('cancel')},
                                        {
                                            text: '我明白,继续更换',
                                            onPress: () => [this.setState({visible: true,})]
                                        },

                                    ])
                                }}
                                value={this.state.cell_number.replace(/(\d{3})(\d{4})(\d{4})/, "$1 $2 $3")}
                                className="order-pay-phone-input"
                            />
                        </div>
                        <div className="order-pay-line-solid"/>

                        {
                            pages.map((elem, index) => {
                                return elem;
                            })
                        }

                        <div className="order-pay-phone">
                            <section>购买数量:</section>
                            <section className="order-pay-buy-right">

                                <section className="order-pay-buy-minus" onClick={() => this.onMinus()}>
                                    <svg>
                                        <use xlinkHref={'#icon-icon_minus'}/>
                                    </svg>
                                </section>
                                <span className="order-pay-buy-amount">
                                    {this.state.amount}
                                </span>
                                <section className="order-pay-buy-plus" onClick={() => this.onPlus()}>
                                    <svg>
                                        <use xlinkHref={'#icon-icon_plus'}/>
                                    </svg>
                                </section>
                            </section>
                        </div>
                        <div className="order-pay-line-solid"/>

                        {(this.state.data.order_form.indexOf('travel_date') != -1) ?
                            <section>
                                <DatePicker
                                    mode="date"
                                    format="YYYY-MM-DD"
                                    title="选择游玩日期"
                                    minDate={minDate}
                                    value={this.state.travel_date}
                                    onChange={date => this.setState({travel_date: date})
                                    }
                                >
                                    <List.Item arrow="horizontal">
                                        <span style={{
                                            fontSize: '.37rem',
                                            color: '#9B9B9B',
                                            marginLeft: '.07rem'
                                        }}>游玩日期：</span></List.Item>
                                </DatePicker>
                                <div className="order-pay-line-solid"/>
                            </section>
                            : null
                        }
                        <div className="order-pay-coupon">
                            <section>使用优惠券:</section>
                            {
                                couponNum > 0 ? <section onClick={this.onBuy('guige')}>
                                    <span>{this.state.coupon ? this.state.coupon.coupon_name : couponNum + '张待使用优惠券'}</span>
                                </section> : <section>
                                    <span>{'暂无优惠券可用'}</span>
                                </section>
                            }

                        </div>
                        <section className="order-img-tips">
                            <img src={pic_receipt_corner_tag}/>
                        </section>
                        <section className="order-pay-img-bg">
                            <img src={receipt_bg_shadow} className="order-img-bg"/>
                        </section>

                    </section>
                </div>
                <div className="order-pay-bottom">
                    <section className="order-pay-price">
                        <span>合计</span>
                        <span>&nbsp;¥&nbsp;</span>
                        <span>{big}</span>
                        <span>.{small}</span>
                    </section>
                    {
                        this.state.showText === true ?
                            <section onClick={() => this.checkPay()}>立即支付</section> : <section>正在支付...</section>
                    }
                </div>

                <Modal
                    popup
                    visible={this.state.guige}
                    onClose={this.onClose('guige')}
                    maskClosable={true}
                    animationType="slide-up"
                >
                    <Coupons
                        CouponsList={this.state.coupon_list}
                        passCoupons={(coupon) => this.passCoupons(coupon)}
                        selling_price={this.state.data.selling_price}
                        amount={this.state.amount}/>
                </Modal>
            </div>
        )
    }
}

class Coupons extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            money: 0,
            item: null,
        };
    }

    //点击优惠券
    onChange(i, item) {
        console.log(i, '------>coupons');
        this.setState({
            item: item,
            money: i,
        });
        if (i.coupon_type == 1) {
            let total_money = this.props.selling_price * this.props.amount;
            console.log(total_money);
            if (i.order_min_total_money > total_money) {
                // this.props.passCoupons(null, '订单金额小于优惠券允许最低金额');
                this.setState({
                    item: null,
                    money: 0,
                });
                Toast.info('订单金额不足' + i.order_min_total_money + '元', 1,);
                return;
            }
        }

        if (i.coupon_type == 2) {
            if (i.order_max_count < this.props.amount) {
                // this.props.passCoupons(null, '购买数量大于优惠券允许数量');
                this.setState({
                    item: null,
                    money: 0,
                });
                Toast.info('每张优惠券仅限' + i.order_max_count + '个商品使用', 1);
                return;

            }

        }
    }

    //  点击确定按钮
    onPress() {
        //选中的优惠券传到支付界面
        this.props.passCoupons(this.state.money);
    }

    render() {
        // console.log(this.props.CouponsList);
        return (
            <div className="order-pay-coupons">
                <section className="order-pay-coupons-title">使用优惠券</section>
                {this.props.CouponsList.map((i, item) => (
                    <section key={item} className="order-pay-coupons-cell" onClick={() => this.onChange(i, item)}>
                        <section className={'order-pay-coupons-name'}>{i.coupon_name}</section>
                        <svg className="order-pay-coupons-img">
                            <use
                                xlinkHref={this.state.item == item ? '#icon-ion_checkmark_circled1' : '#icon-ion_checkmark_circl'}/>
                        </svg>
                    </section>

                ))}
                <section className="order-pay-coupons-bottom" onClick={() => this.onPress()}>
                    <span>关闭</span></section>
            </div>
        )
    }
}
